package com.donghua.controller.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.donghua.entity.LoginTicket;
import com.donghua.entity.User;
import com.donghua.service.UserService;
import com.donghua.util.CookieUtil;
import com.donghua.util.HostHolder;
import com.donghua.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

import static com.donghua.enums.StatusCodeEnum.LOGIN_OVERTIME;
import static com.donghua.enums.StatusCodeEnum.USER_NO_LOGIN;

/**
 * @author Cai Lideng
 * @date 2022年04月23日 上午10:44
 * @description
 */
@Slf4j
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");

        if (ticket != null) {
            // 查询凭证
            String redisKey = RedisKeyUtil.getTicketKey(ticket);
            LoginTicket loginTicket =  (LoginTicket) redisTemplate.opsForValue().get(redisKey);
            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                // 在本次请求中持有用户
                hostHolder.setUser(user);
                log.info("preHandle Interceptor 请求成功，通过拦截器！");
                return true;
            } else {
                JSONObject json = new JSONObject();
                json.put("message", LOGIN_OVERTIME.getMsg());
                json.put("USER_NO_LOGIN", LOGIN_OVERTIME.getCode());
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                response.getWriter().append(json.toJSONString());
                log.info("preHandle Interceptor ticket失效，未通过拦截器！");
                return false;
            }
        } else {
            JSONObject json = new JSONObject();
            json.put("message", USER_NO_LOGIN.getMsg());
            json.put("USER_NO_LOGIN", USER_NO_LOGIN.getCode());
            response.setHeader("Content-Type", "text/html;charset=UTF-8");
            response.getWriter().append(json.toJSONString());
            System.out.println("preHandle Interceptor 用户未登录，未通过拦截器！");
            return false;
        }
    }
}
